from rest_framework import permissions
from choice.models import Snippet
from rest_framework import mixins
from rest_framework import generics
from choice.serializers import (SnippetSerializer, UserSerialzier)
from choice.permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User

from rest_framework.decorators import api_view, detail_route
from rest_framework.response import Response
from rest_framework.reverse import reverse


class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )


class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerialzier


class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerialzier

sql = "select url,count(client_mac) as nums from app_urlcollect  where report_time BETWEEN '%s' AND '%s' AND router_mac IN(select r.mac from app_routers as r,app_users as u where r.owner=u.id and u.area_id=%d) " \
          "GROUP BY url ORDER BY nums DESC LIMIT %d"

